# -*- coding: utf-8; -*-
#
# dput/methods/ftp.py
# Part of ‘dput’, a Debian package upload toolkit.
#
# Copyright © 2015 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2008–2013 Y Giridhar Appaji Nag <appaji@debian.org>
# Copyright © 2007 Thomas Viehmann <tv@beamnet.de>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of that license or any later version.

""" Implementation for FTP upload method. """

from __future__ import absolute_import

import os
import sys
import ftplib
import getpass

from ..helper import dputhelper


def upload(
        fqdn, login, incoming, files_to_upload, debug, ftp_mode,
        progress=0, port=21):
    """ Upload the files via FTP.

        (Could need a bit more error-checking.)

        """

    try:
        ftp_connection = ftplib.FTP()
        ftp_connection.connect(fqdn, port)
        if debug:
            print "D: FTP-Connection to host: %s" % fqdn
    except ftplib.all_errors as e:
        print "Connection failed, aborting. Check your network", e
        sys.exit(1)
    prompt = login + "@" + fqdn + " password: "
    if login == 'anonymous':
        password = 'dput@packages.debian.org'
    else:
        password = getpass.getpass(prompt)
    try:
        ftp_connection.login(login, password)
    except ftplib.error_perm:
        print "Wrong Password"
        sys.exit(1)
    except EOFError:
        print "Server closed the connection"
        sys.exit(1)
    ftp_connection.set_pasv(ftp_mode == 1)
    try:
        ftp_connection.cwd(incoming)
    except ftplib.error_perm as e:
        if e.args and e.args[0][:3] == '550':
            print "Directory to upload to does not exist."
            sys.exit(1)
        else:
            raise
    if debug:
        print "D: Directory to upload to: %s" % incoming
    for afile in files_to_upload:
        path_to_package, package_name = os.path.split(afile)
        try:
            if debug:
                print "D: Uploading File: %s" % afile
            if progress:
                try:
                    size = os.stat(afile).st_size
                except:
                    size = -1
                    if debug:
                        print "D: Determining size of file '%s' failed" % afile
            f = open(afile, 'r')
            if progress:
                f = dputhelper.FileWithProgress(
                        f, ptype=progress,
                        progressf=sys.stdout,
                        size=size)
            sys.stdout.write("  Uploading %s: " % package_name)
            sys.stdout.flush()
            ftp_connection.storbinary(
                    'STOR ' + package_name,
                    f, 1024)
            f.close()
            sys.stdout.write("done.\n")
            sys.stdout.flush()
        except ftplib.all_errors as e:
            print "%s" % (str(e))
            if (
                    isinstance(e, ftplib.Error)
                    and e.args and e.args[0][:3] == '553'):
                print (
                        "Leaving existing %s on the server and continuing"
                        % (package_name))
                print (
                        "NOTE: This existing file may have been"
                        " previously uploaded partially.\n"
                        "For official Debian upload queues,"
                        " the dcut(1) utility can be\n"
                        "used to remove this file, and after"
                        " an acknowledgement mail is\n"
                        "received in response to dcut,"
                        " the upload can be re-initiated.")
                continue
            elif (
                    isinstance(e, ftplib.Error)
                    and e.args and e.args[0][:1] == '5'):
                print (
                        "Note: This error might indicate a problem with"
                        " your passive_ftp setting.\n"
                        "Please consult dput.cf(5) for details on"
                        " this configuration option.")
            if debug:
                print (
                        "D: Should exit silently now, but"
                        " will throw exception for debug.")
                raise
            sys.exit(1)
    try:
        ftp_connection.quit()
    except Exception as e:
        if debug:
            print "D: Exception %s while attempting to quit ftp session." % e
            print "D: Throwing an exception for debugging purposes."
            raise


# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :
